/*
 * Copyright 2013 Sigurd Randoll <srandoll@digiway.de>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.digiway.rapidbreeze.server.infrastructure.rest.download;

import de.digiway.rapidbreeze.shared.rest.download.DownloadResource;
import com.sun.jersey.api.JResponse;
import de.digiway.rapidbreeze.server.model.download.Download;
import de.digiway.rapidbreeze.server.model.download.DownloadManager;
import de.digiway.rapidbreeze.shared.rest.ResourceLocation;
import static de.digiway.rapidbreeze.shared.rest.download.DownloadStatus.PAUSE;
import static de.digiway.rapidbreeze.shared.rest.download.DownloadStatus.RUNNING;
import static de.digiway.rapidbreeze.shared.rest.download.DownloadStatus.WAITING;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;

/**
 *
 * @author Sigurd Randoll <srandoll@digiway.de>
 */
@Path(ResourceLocation.DOWNLOAD_RESOURCE_PATH)
public class DownloadManagerResource {

    @Context
    DownloadManager downloadManager;
    private static final Logger LOG = Logger.getLogger(DownloadManagerResource.class.getName());

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public JResponse<List<DownloadResource>> getDownloads() {
        List<DownloadResource> list = new ArrayList<>();
        for (Download download : new ArrayList<>(downloadManager.getDownloads())) {
            DownloadResource dto = DownloadResourceFactory.create(download);
            list.add(dto);
        }
        return new JResponse.JResponseBuilder<List<DownloadResource>>().status(Status.OK).entity(list).build();
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_XML)
    public JResponse getDownload(@PathParam(value = "id") String identifier) {
        if (downloadManager.hasDownload(identifier)) {
            Download download = downloadManager.getDownload(identifier);
            DownloadResource downloadResource = DownloadResourceFactory.create(download);
            return JResponse.ok(downloadResource).build();
        }
        return JResponse.status(Status.NOT_FOUND).build();
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.APPLICATION_XML)
    public JResponse add(@Context UriInfo uriInfo, String urlString) {
        URL url;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException ex) {
            return JResponse.status(Status.BAD_REQUEST.getStatusCode()).entity("Cannot parse given URL:" + urlString + ". " + ex.getLocalizedMessage()).build();
        }
        if (!downloadManager.canHandleUrl(url)) {
            return JResponse.status(Status.BAD_REQUEST).entity("The server cannot handle the download url:" + url.toString()).build();
        }

        Download download = downloadManager.addUrl(url);
        DownloadResource resource = DownloadResourceFactory.create(download);
        URI uri = uriInfo.getBaseUriBuilder().path(DownloadManagerResource.class).path("/{id}").build(download.getIdentifier());

        return JResponse.ok(resource).status(Status.CREATED).location(uri).build();
    }

    @DELETE
    @Path("/{id}")
    @Consumes(MediaType.APPLICATION_XML)
    public JResponse remove(@PathParam(value = "id") String identifier) {
        if (!downloadManager.hasDownload(identifier)) {
            return JResponse.status(Status.NOT_FOUND).build();
        }

        try {
            Download download = downloadManager.getDownload(identifier);
            downloadManager.removeDownload(download);
            return JResponse.status(Status.OK).build();
        } catch (RuntimeException ex) {
            LOG.log(Level.SEVERE, "An exception occured during delete of download instance.", ex);
        }
        return JResponse.serverError().build();
    }

    @PUT
    @Path("/{id}")
    @Consumes(MediaType.APPLICATION_XML)
    public JResponse update(final DownloadResource resource) {
        if (!downloadManager.hasDownload(resource.getIdentifier())) {
            return JResponse.status(Status.NOT_FOUND).build();
        }

        Download download = downloadManager.getDownload(resource.getIdentifier());

        // TODO: Nasty if clause:
        if (!download.getDownloadStatus().equals(resource.getDownloadStatus())) {

            switch (download.getDownloadStatus()) {
                case WAITING:
                case ERROR:
                    switch (resource.getDownloadStatus()) {
                        case RUNNING:
                            downloadManager.startDownload(download);
                            break;
                    }
                    break;
                case RUNNING:
                    switch (resource.getDownloadStatus()) {
                        case PAUSE:
                            downloadManager.pauseDownload(download);
                            break;
                        case WAITING:
                            downloadManager.waitDownload(download);
                            break;
                    }
                    break;
                case PAUSE:
                    switch (resource.getDownloadStatus()) {
                        case RUNNING:
                            downloadManager.startDownload(download);
                            break;
                        case WAITING:
                            downloadManager.waitDownload(download);
                            break;
                    }
                    break;
            }
        }

        return JResponse.ok().build();
    }
}